package com.example.studyproject.loginInterceptor;

import com.example.studyproject.enums.NotLoginWhiteListInterfaceEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @program: SalaryProject
 * @description: 自定义拦截器
 * @author: kangwei
 * @create: 2023-03-10 10:08
 **/
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("自定义拦截器开始");
        // 免登录拦截
        if (NotLoginWhiteListInterfaceEnum.isNotLogin(request.getRequestURI())) {
            return true;
        }
        // 登录校验
        HttpSession session = request.getSession(false);
        if (null != session && null != session.getAttribute("userinfo")) {
            return true;
        }
        // 没有登录
        response.setStatus(401); // 没有访问权限
        // 返回登录页面
        response.sendRedirect("/user/login.html");
        return false;
    }
}
